package hust.iamk.lock;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.cooliris.media.GridLayer;
import com.cooliris.media.LocalDataSource;

public class LockFileTask extends AsyncTask<String, String, String> {
	
	ProgressDialog pdLockFile;

	Context mContext;
	GridLayer mGridLayer;
	ArrayList<String> arrFilePath;
	long totalLengthFile = 0;
	int currentLen = 0;
	
	boolean LOCK_FAILED = true;
	
	public LockFileTask(Context mContext, ArrayList<String> arrFilePath, GridLayer mGridLayer) {
		// TODO Auto-generated constructor stub
		this.arrFilePath = arrFilePath;
		this.mContext = mContext;
		this.mGridLayer = mGridLayer;
		// Get all length file
		for(int i = 0; i < arrFilePath.size();i++){
			File f = new File(arrFilePath.get(i));
			if(f.exists()){
				totalLengthFile += f.length();
			}
		}
	}
	
	@SuppressWarnings("deprecation")
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		pdLockFile = new ProgressDialog(mContext);
		pdLockFile.setMessage("Locking file. Please wait...");
		pdLockFile.setIndeterminate(false);
		pdLockFile.setMax(100);
		pdLockFile.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pdLockFile.setCancelable(false);
		pdLockFile.setCanceledOnTouchOutside(false);
		pdLockFile.setButton("Do in background", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            	pdLockFile.dismiss();
            }
        });
		pdLockFile.show();
	}

	/**
	 * Lock file in background thread
	 * */
	@Override
	protected String doInBackground(String... mItem) {
		try {
			for(int i = 0; i < arrFilePath.size(); i++){
				String fileNameSrc = SecurityFileUtils.getFileName(arrFilePath.get(i), 0);
				File fsrc = new File(arrFilePath.get(i));
				File fdes = new File(LocalDataSource.LOCK_BUCKET_NAME +"/" + fileNameSrc.replace(".", "iamk"));
				Log.d("lock", fsrc.getAbsolutePath() + " // " + fdes.getAbsolutePath());
				if(!fsrc.getAbsolutePath().toString().equals(fdes.getAbsolutePath().toString())){
		            InputStream is=new FileInputStream(fsrc);
		            OutputStream os=new FileOutputStream(fdes);
		            byte[] buff=new byte[1024];
		            int len;
		            while((len = is.read(buff)) > 0){
		                os.write(buff,0,len);
		                currentLen += len;
		                publishProgress(""+(int)((currentLen*100)/totalLengthFile));
		            }
		            is.close();
		            os.close();
		        }
			}
			LOCK_FAILED = false;
		} catch (Exception e) {
			LOCK_FAILED = true;
			e.printStackTrace();
		} 
        return null;
	}
	
	/**
	 * Updating progress bar
	 * */
	protected void onProgressUpdate(String... progress) {
		// setting progress percentage
		pdLockFile.setProgress(Integer.parseInt(progress[0]));
   }

	@Override
	protected void onPostExecute(String mItem) {
		if (pdLockFile != null && pdLockFile.isShowing()) 
			 pdLockFile.dismiss();
		// Delete original file
		Log.d("lock", "Lock failed: " + LOCK_FAILED);
		if(!LOCK_FAILED){
			mGridLayer.deleteSelection();
		}
	}
}


